#include "Main.h"
#include "Include/student_pub.h"
#include "Include/course_pub.h"
#include "Include/data_input.h"
#include "Include/log_pub.h"
#include <stdlib.h>  
#include <stdio.h>
#include <string.h>

// 释放链表内存
void free_student_list(StudentList head) {
    StudentNode *p = head->next;
    while (p) {
        StudentNode *temp = p;
        p = p->next;
        free(temp);
    }
    free(head);
}

void free_course_list(CourseList head) {
    CourseNode *p = head->next;
    while (p) {
        CourseNode *temp = p;
        p = p->next;
        free(temp);
    }
    free(head);
}

// 学生选课功能
void student_select_course(StudentList s_head, CourseList c_head) {
    char stu_id[20], course_id[20];
    printf("请输入学生学号：");
    scanf("%s", stu_id);
    printf("请输入课程编号：");
    scanf("%s", course_id);
    clear_input_buffer();

    // 查找学生和课程
    StudentNode *stu = NULL;
    CourseNode *course = NULL;
    StudentNode *s_p = s_head->next;
    CourseNode *c_p = c_head->next;
    while (s_p) {
        if (strcmp(s_p->id, stu_id) == 0) {
            stu = s_p;
            break;
        }
        s_p = s_p->next;
    }
    while (c_p) {
        if (strcmp(c_p->id, course_id) == 0) {
            course = c_p;
            break;
        }
        c_p = c_p->next;
    }

    // 校验合法性
    if (!stu) { printf("选课失败：学生不存在！\n"); return; }
    if (!course) { printf("选课失败：课程不存在！\n"); return; }
    if (course->selected >= course->max) { printf("选课失败：课程已达人数上限！\n"); return; }

    // 检查是否已选该课程
    int is_selected = 0;
    char temp_ids[200];
    strcpy(temp_ids, stu->course_ids);
    char *token = strtok(temp_ids, ",");
    while (token) {
        if (strcmp(token, course_id) == 0) {
            is_selected = 1;
            break;
        }
        token = strtok(NULL, ",");
    }
    if (is_selected) {
        printf("选课失败：已选该课程！\n");
        return;
    }

    // 执行选课逻辑
    if (strlen(stu->course_ids) == 0) {
        strcpy(stu->course_ids, course_id);  // 首次选课
    } else {
        strcat(stu->course_ids, ",");        // 非首次加逗号
        strcat(stu->course_ids, course_id);
    }
    stu->total_credit += course->credit;
    course->selected++;

    printf("选课成功！当前总学分：%d\n", stu->total_credit);
    char log[256];
    sprintf(log, "学生%s选课程%s，学分+%d", stu_id, course_id, course->credit);
    write_log(log);
    save_data(s_head, c_head);
}

// 学生退课功能
void student_drop_course(StudentList s_head, CourseList c_head) {
    char stu_id[20], course_id[20];
    printf("请输入学生学号：");
    scanf("%s", stu_id);
    printf("请输入课程编号：");
    scanf("%s", course_id);
    clear_input_buffer();

    // 查找学生和课程
    StudentNode *stu = NULL;
    CourseNode *course = NULL;
    StudentNode *s_p = s_head->next;
    CourseNode *c_p = c_head->next;
    while (s_p) {
        if (strcmp(s_p->id, stu_id) == 0) {
            stu = s_p;
            break;
        }
        s_p = s_p->next;
    }
    while (c_p) {
        if (strcmp(c_p->id, course_id) == 0) {
            course = c_p;
            break;
        }
        c_p = c_p->next;
    }

    // 校验合法性
    if (!stu) { printf("退课失败：学生不存在！\n"); return; }
    if (!course) { printf("退课失败：课程不存在！\n"); return; }

    // 检查是否已选
    char *pos = NULL;
    char temp_ids[200];
    strcpy(temp_ids, stu->course_ids);
    char *token = strtok(temp_ids, ",");
    while (token) {
        if (strcmp(token, course_id) == 0) {
            pos = strstr(stu->course_ids, course_id);
            break;
        }
        token = strtok(NULL, ",");
    }
    if (!pos) {
        printf("退课失败：未选该课程！\n");
        return;
    }

    // 确保是完整匹配
    int is_valid = 0;
    int len = strlen(course_id);
    if (pos == stu->course_ids) {  // 开头
        if (pos[len] == '\0' || pos[len] == ',') is_valid = 1;
    } else if (pos[-1] == ',') {  // 中间或结尾
        if (pos[len] == '\0' || pos[len] == ',') is_valid = 1;
    }
    if (!is_valid) {
        printf("退课失败：未选该课程！\n");
        return;
    }

    // 移除课程ID
    int del_len = len;
    if (pos[len] == ',') del_len++;  // 包含逗号
    memmove(pos, pos + del_len, strlen(pos + del_len) + 1);

    // 更新学分和课程人数
    stu->total_credit -= course->credit;
    if (stu->total_credit < 0) stu->total_credit = 0;
    course->selected--;
    if (course->selected < 0) course->selected = 0;

    printf("退课成功！当前总学分：%d\n", stu->total_credit);
    char log[256];
    sprintf(log, "学生%s退课程%s，学分-%d", stu_id, course_id, course->credit);
    write_log(log);
    save_data(s_head, c_head);
}

// 学生信息管理子菜单
void student_menu(StudentList s_head) {
    int choice;
    while (1) {
        printf("\n 学生信息管理 \n");
        printf("1. 新增学生\n2. 删除学生\n3. 修改学生姓名\n");
        printf("4. 按学号查询详情\n5. 按姓名查询\n6. 查看所有学生\n7. 返回上一级\n");
        printf("请选择（1-7）：");
        scanf("%d", &choice);
        clear_input_buffer();
        switch (choice) {
            case 1: add_student(s_head); break;
            case 2: del_student(s_head); break;
            case 3: modify_student(s_head); break;
            case 4: query_student_by_id(s_head); break;
            case 5: query_student_by_name(s_head); break;
            case 6: show_all_students(s_head); break;
            case 7: return;
            default: printf("无效选项！请重新选择\n");
        }
    }
}

// 课程信息管理子菜单
void course_menu(CourseList c_head, StudentList s_head) {
    int choice;
    while (1) {
        printf("\n 课程信息管理 \n");
        printf("1. 新增课程\n2. 删除课程\n3. 修改课程信息\n");
        printf("4. 查看课程详情\n5. 查看所有课程\n6. 返回上一级\n");
        printf("请选择（1-6）：");
        scanf("%d", &choice);
        clear_input_buffer();
        switch (choice) {
            case 1: add_course(c_head); break;
            case 2: del_course(&c_head, s_head); break;
            case 3: modify_course(c_head); break;
            case 4: query_course_detail(c_head, s_head); break;
            case 5: show_all_courses(c_head); break;
            case 6: return;
            default: printf("无效选项！请重新选择\n");
        }
    }
}

// 主菜单
void show_main_menu() {
    printf("\n学生选课系统\n");
    printf("1. 学生信息管理\n2. 课程信息管理\n");
    printf("3. 学生选课\n4. 学生退课\n5. 退出系统\n");
    printf("请选择功能（1-5）：");
}

int main() {
    // 初始化链表
    StudentList s_head;
    CourseList c_head;
    init_stu_list(&s_head);
    init_course_list(&c_head);

    // 加载数据
    if (getenv("PRODUCT_TYPE") && strcmp(getenv("PRODUCT_TYPE"), "file") == 0) {
        printf("产品形态：文件录入版\n");
        load_data(s_head, c_head);
    } else {
        printf("产品形态：命令行录入版 \n");
        input_data_cmd(s_head, c_head);
    }

    // 主循环
    int choice;
    while (1) {
        show_main_menu();
        scanf("%d", &choice);
        clear_input_buffer();
        switch (choice) {
            case 1: student_menu(s_head); break;
            case 2: course_menu(c_head, s_head); break;
            case 3: student_select_course(s_head, c_head); break;
            case 4: student_drop_course(s_head, c_head); break;
            case 5:
                save_data(s_head, c_head);
                printf("感谢使用，再见！\n");
                write_log("系统退出");
                // 释放内存
                free_student_list(s_head);
                free_course_list(c_head);
                return 0;
            default: printf("无效选项！请重新选择\n");
        }
    }
}
